import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/constants/app_constants.dart';
import '../providers/anime_provider.dart';
import '../providers/content_filter_provider.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage>
    with TickerProviderStateMixin {
  late AnimationController _logoController;
  late AnimationController _textController;
  late AnimationController _progressController;
  
  late Animation<double> _logoScaleAnimation;
  late Animation<double> _logoOpacityAnimation;
  late Animation<Offset> _textSlideAnimation;
  late Animation<double> _textOpacityAnimation;
  late Animation<double> _progressAnimation;
  
  String _loadingText = '正在初始化...';
  double _loadingProgress = 0.0;
  
  final List<String> _loadingSteps = [
    '正在初始化...',
    '正在加载热门动漫...',
    '正在加载最新内容...',
    '即将完成...'
  ];
  
  int _currentStep = 0;

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _startPreloading();
  }

  void _initAnimations() {
    // Logo动画控制器
    _logoController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    
    // 文字动画控制器
    _textController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );
    
    // 进度条动画控制器
    _progressController = AnimationController(
      duration: const Duration(milliseconds: AppConstants.splashDuration),
      vsync: this,
    );
    
    // Logo缩放动画
    _logoScaleAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _logoController,
      curve: Curves.elasticOut,
    ));
    
    // Logo透明度动画
    _logoOpacityAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _logoController,
      curve: const Interval(0.0, 0.6, curve: Curves.easeInOut),
    ));
    
    // 文字滑动动画
    _textSlideAnimation = Tween<Offset>(
      begin: const Offset(0, 1),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _textController,
      curve: Curves.easeOutBack,
    ));
    
    // 文字透明度动画
    _textOpacityAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _textController,
      curve: Curves.easeInOut,
    ));
    
    // 进度条动画
    _progressAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _progressController,
      curve: Curves.easeInOut,
    ));
    
    // 启动动画序列
    _startAnimations();
  }

  void _startAnimations() async {
    // 首先启动Logo动画
    _logoController.forward();
    
    // 延迟启动文字动画
    await Future.delayed(const Duration(milliseconds: 800));
    _textController.forward();
    
    // 启动进度条动画
    _progressController.forward();
    
    // 监听进度变化
    _progressController.addListener(() {
      setState(() {
        _loadingProgress = _progressAnimation.value;
      });
    });
  }

  void _startPreloading() async {
    final animeProvider = Provider.of<AnimeProvider>(context, listen: false);
    
    const minShowTime = Duration(milliseconds: 2500); // 最小显示时间
    final stopwatch = Stopwatch()..start();
    
    try {
      // 第一步：初始化内容过滤器
      _updateLoadingStep(0);
      await Future.delayed(const Duration(milliseconds: 400));
      
      // 第二步：初始化主页数据（包含缓存优化）
      _updateLoadingStep(1);
      await animeProvider.initializeData();
      await Future.delayed(const Duration(milliseconds: 600));
      
      // 第三步：预加载最新剧集
      _updateLoadingStep(2);
      await animeProvider.fetchRecentEpisodes();
      await Future.delayed(const Duration(milliseconds: 600));
      
      // 第四步：完成
      _updateLoadingStep(3);
      
      // 确保最小显示时间
      final elapsed = stopwatch.elapsedMilliseconds;
      if (elapsed < minShowTime.inMilliseconds) {
        await Future.delayed(Duration(milliseconds: minShowTime.inMilliseconds - elapsed));
      }
      
      if (mounted) {
        Navigator.of(context).pushReplacementNamed(RouteConstants.home);
      }
      
    } catch (e) {
      // 如果预加载失败，仍然跳转到主页
      debugPrint('预加载数据失败: $e');
      
      // 确保最小显示时间
      final elapsed = stopwatch.elapsedMilliseconds;
      if (elapsed < minShowTime.inMilliseconds) {
        await Future.delayed(Duration(milliseconds: minShowTime.inMilliseconds - elapsed));
      }
      
      if (mounted) {
        Navigator.of(context).pushReplacementNamed(RouteConstants.home);
      }
    } finally {
      stopwatch.stop();
    }
  }
  
  void _updateLoadingStep(int step) {
    if (step < _loadingSteps.length) {
      setState(() {
        _currentStep = step;
        _loadingText = _loadingSteps[step];
      });
    }
  }

  @override
  void dispose() {
    _logoController.dispose();
    _textController.dispose();
    _progressController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDarkMode = theme.brightness == Brightness.dark;
    
    return Scaffold(
      backgroundColor: isDarkMode 
          ? theme.scaffoldBackgroundColor 
          : const Color(0xFF1A1A2E),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: isDarkMode
                ? [
                    theme.scaffoldBackgroundColor,
                    theme.scaffoldBackgroundColor.withOpacity(0.8),
                  ]
                : [
                    const Color(0xFF1A1A2E),
                    const Color(0xFF16213E),
                    const Color(0xFF0F3460),
                  ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Logo区域
                      AnimatedBuilder(
                        animation: _logoController,
                        builder: (context, child) {
                          return Opacity(
                            opacity: _logoOpacityAnimation.value,
                            child: Transform.scale(
                              scale: _logoScaleAnimation.value,
                              child: Container(
                                width: 120,
                                height: 120,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(25),
                                  gradient: LinearGradient(
                                    begin: Alignment.topLeft,
                                    end: Alignment.bottomRight,
                                    colors: [
                                      theme.primaryColor,
                                      theme.primaryColor.withOpacity(0.7),
                                    ],
                                  ),
                                  boxShadow: [
                                    BoxShadow(
                                      color: theme.primaryColor.withOpacity(0.3),
                                      blurRadius: 20,
                                      spreadRadius: 5,
                                    ),
                                  ],
                                ),
                                child: const Icon(
                                  Icons.play_circle_filled,
                                  size: 60,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                      
                      const SizedBox(height: 30),
                      
                      // 应用名称
                      AnimatedBuilder(
                        animation: _textController,
                        builder: (context, child) {
                          return SlideTransition(
                            position: _textSlideAnimation,
                            child: FadeTransition(
                              opacity: _textOpacityAnimation,
                              child: Column(
                                children: [
                                  Text(
                                    AppConstants.appName,
                                    style: TextStyle(
                                      fontSize: 36,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.white,
                                      letterSpacing: 2,
                                      shadows: [
                                        Shadow(
                                          color: theme.primaryColor.withOpacity(0.5),
                                          blurRadius: 10,
                                          offset: const Offset(0, 2),
                                        ),
                                      ],
                                    ),
                                  ),
                                  const SizedBox(height: 8),
                                  Text(
                                    '探索无限精彩动漫世界',
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.white70,
                                      letterSpacing: 1,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
              
              // 底部加载区域
              Padding(
                padding: const EdgeInsets.all(40),
                child: Column(
                  children: [
                    // 加载进度条
                    Container(
                      width: double.infinity,
                      height: 4,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(2),
                        color: Colors.white.withOpacity(0.2),
                      ),
                      child: AnimatedBuilder(
                        animation: _progressAnimation,
                        builder: (context, child) {
                          return FractionallySizedBox(
                            alignment: Alignment.centerLeft,
                            widthFactor: _progressAnimation.value,
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(2),
                                gradient: LinearGradient(
                                  colors: [
                                    theme.primaryColor,
                                    theme.primaryColor.withOpacity(0.7),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                    
                    const SizedBox(height: 16),
                    
                    // 加载文字
                    AnimatedSwitcher(
                      duration: const Duration(milliseconds: 300),
                      child: Text(
                        _loadingText,
                        key: ValueKey(_loadingText),
                        style: const TextStyle(
                          fontSize: 14,
                          color: Colors.white70,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
} 